""" api_handler.py

This module provides the entry point for the AppEngine InFlightXt application.

   Copyright 2011 Bravo369.org

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

author = Mike Meade (mmeade@google.com)
"""

# General imports
import logging

# Application imports
import api
from forms import error_pages
from utils import html_utils

# Framework imports
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app


class ApiHandler(webapp.RequestHandler):
  """Main API Handler."""

  # Add the per-application authorization token here
  _AUTH_TOKEN = ''

  def put(self):
    """Implement the PUT command.  The result of the PUT operation."""
    self.post("put")

  def post(self):
    """Implement the POST command.  The result of the POST operation."""
    self.doApiMethod("post")

  def get(self):
    """Implement the GET command."""
    self.doApiMethod("get")

  def delete(self):
    """Implement the DELETE command."""
    self.doApiMethod("delete")

  def doApiMethod(self, method):
    """Handle the API method.

    Args:
      method: The method to handle.
    """
    query = html_utils.getAllQueries(self.request.query_string)
    logging.info(str(query))
    if 'method' not in query:
      self.respondBadQuery()
    auth = self.request.headers.get('Authorization')
    if not auth or auth != self._AUTH_TOKEN:
      self.respondNotAuthorized()
      return
    try:
      methodClass = query['method']
      logging.info(methodClass)
      methodName = method + methodClass.capitalize()
      logging.info(methodName)
      handler = api.Handlers.getHandler(methodClass, methodName)
      logging.info('Handler class is %r', handler.__name__)
      handler(self)
    except api.NoHandlerFoundError:
      logging.error('No handler found for: %r', methodName)
      self.respondBadQuery()
    except Exception, e:
      logging.error('Exception %r', e)
      self.respondBadQuery()

  def respondNotAuthorized(self):
    """Handle 401 Not Authorized responses."""
    logging.error('Not authorized')
    self.response.set_status(401)
    self.response.out.write(error_pages.NOT_AUTHORIZED)

  def respondBadQuery(self):
    """Handle 405 Bad Query responses."""
    self.response.set_status(405)
    self.response.out.write(error_pages.BAD_REQUEST)


application = webapp.WSGIApplication(
    [('/api\.html', ApiHandler)], debug=True)


def main():
  run_wsgi_app(application)


if __name__ == '__main__':
  main()
